<?php

/**
 * Albireo Kernel
 *
 * @copyright  Copyright (c) 2010 Albireo Solutions
 * @package    Kernel
 */

use Nette\Object;
use \dibi;

/**
 * KernelAclModel 
 *
 * @author Albireo Solutions
 */

class KernelAclModel extends Object {

    const ACL_TABLE = 'acl';
    const PRIVILEGES_TABLE = 'privileges';
    const RESOURCES_TABLE = 'resources';
    const ROLES_TABLE = 'roles';

    /**
     * @return array of roles to add in KernelAcl
     */
    public function getRoles() {
        return dibi::fetchAll('
                SELECT r1.name, r2.name as parent_name
                FROM ['. self::ROLES_TABLE . '] r1
                LEFT JOIN ['. self::ROLES_TABLE . '] r2 ON (r1.parent_id = r2.id)
            ');
    }

    /**
     * @return array of resources to add in KernelAcl
     */
    public function getResources() {
        return dibi::fetchAll('
                SELECT name FROM ['. self::RESOURCES_TABLE . ']
            ');
    }

    /**
     * @return array of rules to add in KernelAcl
     */
    public function getRules() {
        $query = dibi::query('
                SELECT
                    a.allowed as allowed,
                    ro.name as role,
                    re.name as resource,
                    p.name as privilege
                FROM [' . self::ACL_TABLE . '] a
                JOIN [' . self::ROLES_TABLE . '] ro ON (a.role_id = ro.id)
                LEFT JOIN [' . self::RESOURCES_TABLE . '] re ON (a.resource_id = re.id)
                LEFT JOIN [' . self::PRIVILEGES_TABLE . '] p ON (a.privilege_id = p.id)
                ORDER BY a.id ASC
            ');

        $fetched = $query->fetchAll();
        unset($query);
        return $fetched;
    }
}